package tools

import (
	"bufio"
	"fmt"
	"gitee.com/youbeiwuhuan/go-xxljob-executor/biz/model"
	"gitee.com/youbeiwuhuan/go-xxljob-executor/global"
	"gitee.com/youbeiwuhuan/go-xxljob-executor/utils/files"
	"go.uber.org/zap"
	"io"
	"os"
	"time"
)

const (
	LOG_FILE_FOEDERE = "/jobhandler"
)

type XxlJobFileLogger struct {
	logBasePath string
	logId       int64
	triggerDate time.Time
}

func NewXxlJobFileAppender(logId int64, triggerDate time.Time) *XxlJobFileLogger {

	return &XxlJobFileLogger{
		logBasePath: global.XxlLogPath + LOG_FILE_FOEDERE,
		logId:       logId,
		triggerDate: triggerDate,
	}
}

func (t *XxlJobFileLogger) Log(appendLog string) {
	if "" == appendLog {
		return
	}

	f := files.OpenFileForAppend(t.makeLogFileName())
	defer func(f *os.File) {
		if nil != f {
			f.Close()
		}
	}(f)

	io.WriteString(f, appendLog+"\r\n")

}

func (t *XxlJobFileLogger) makeLogFileName() string {

	logPath := t.logBasePath + "/" + getDateFoderName(t.triggerDate)
	global.Logger.Debug("******************" + logPath)
	files.CreateDirIfNotExists(logPath)

	return logPath + "/" + fmt.Sprintf("%d", t.logId) + ".log"
}

func MakeLogFileName(logId int64, triggerDate time.Time) string {
	logPath := global.XxlLogPath + LOG_FILE_FOEDERE + "/" + getDateFoderName(triggerDate)

	return logPath + "/" + fmt.Sprintf("%d", logId) + ".log"
}

func ReadLog(logFileName string, fromLineNum int32) model.LogResult {
	f, err := os.Open(logFileName)
	if err != nil {
		global.Logger.Error("", zap.Any("err", err))
		return model.LogResult{
			FromLineNum: fromLineNum,
			ToLineNum:   fromLineNum,
			LogContent:  "",
			IsEnd:       true,
		}
	}
	defer f.Close()

	toLineNum := fromLineNum + 10000

	rd := bufio.NewReader(f)
	logContent := ""
	var i int32 = 0
	isEnd := false
	for ; i < toLineNum; i = i + 1 {
		line, err := rd.ReadString('\n') //以'\n'为结束符读入一行

		if err != nil || io.EOF == err {
			global.Logger.Error("", zap.Any("err", err))
			isEnd = true
			break
		}

		fmt.Println(line)
		logContent = logContent + line

	}

	return model.LogResult{
		FromLineNum: fromLineNum,
		ToLineNum:   i,
		LogContent:  logContent,
		IsEnd:       isEnd,
	}

}

func getDateFoderName(timeObj time.Time) string {
	year := timeObj.Year()
	month := timeObj.Month()
	day := timeObj.Day()
	//hour := timeObj.Hour()
	//minute := timeObj.Minute()
	//second := timeObj.Second()
	//fmt.Printf("%02d-%02d-%02d  %02d:%02d:%02d\n", year, month, day, hour, minute, second)
	return fmt.Sprintf("%02d-%02d-%02d", year, month, day)
}
